//
//  ListSchedule.m
//  FMS
//
//  Created by Steven on 10/11/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "ListScheduleViewController.h"
#import "CalendarScheduleViewController.h"
#import "ScheduleFilterViewController.h"
#import "ScheduleInspectionViewController.h"
#import "BuildingMgmtViewController.h"
#import "ScheduleBaseLite.h"
#import "UIScrollView+ScrollView.h"

#define WIDTH_COLUMN_ONE  200
#define WIDTH_COLUMN_TWO  320
#define WIDTH_COLUMN_THREE  180
#define WIDTH_COLUMN_FOUR  254

@interface ListScheduleViewController ()

@end
enum IndexSelectDate {
    StartDateIndex = 1,
    EndDateIndex
    };
enum ScheduleCellTag {
    Category_Program_Schedule_Tag = 5,
    Maintenance_Type_Schedule_Tag,
    Item_Type_Schedule_Tag,
    NextDone_Schedule_Tag
    };
@implementation ListScheduleViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        
        [self addLoadingView];
        [self addTopBar];
        if (self.navBar)
        {
            self.navBar.navBarViewDelegate = self;
            [self.navBar.leftButton setBackgroundImage:[UIImage imageNamed:@"btnCancel.png"] forState:UIControlStateNormal];
            [self.navBar.rightButton setBackgroundImage:[UIImage imageNamed:@"btnAddNew.png"] forState:UIControlStateNormal];
            
            UIButton *btnSwitchCalendar = [UIButton buttonWithType:UIButtonTypeCustom];
            btnSwitchCalendar.frame = CGRectMake(1024-88, 0, 44, 44);
            
            [btnSwitchCalendar addTarget:self action:@selector(btnSwitchCalendarClick:) forControlEvents:UIControlEventTouchUpInside];
            [btnSwitchCalendar setBackgroundImage:[UIImage imageNamed:@"btnCalendar.png"] forState:UIControlStateNormal];
            [self.navBar addSubview:btnSwitchCalendar];
            
            self.navBar.titleLabel.text = [dictLanguage objectForKey:@"schedule.title-schedule"];
        }
        
    }
    return self;
}

- (void)hiddenLoading{
    [self showHiddenActivityProgess:NO];
}
- (NSMutableArray *)fitlerScheduleByContent{
    
    NSMutableArray *array;
    
    
//    if ([[dictCategory objectForKey:@"index"] intValue] == 0)
//        array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database];
//    else
//        if ([[dictCategory objectForKey:@"index"] intValue] == Inspection_Category_Type)
//            array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database byIdCategory:Inspection];
//        else
//        {
//            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"categoryId",[dictCategory objectForKey:@"index"],@"categoryTypeId", nil];
//            array = [ScheduleBaseLite queryListsInDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database byCategory:dict];
//        }
    return array;
}
- (void)listScheduleByType{

//    [arraySchedule removeAllObjects];
    
    NSMutableArray *array;
    isLoadMore = NO;
    //check role admin/owner/ma to list all and contractor to listy contractor self
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
    role = [role lowercaseString];
    if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]){
        if ([[dictCategory objectForKey:@"index"] intValue] == 0)
            array = [ScheduleBaseLite queryScheduleInStart:startDateStr endDate:endDateStr from:indexSchedule numberPage:NUMBER_ROW_PAGE];
        else
            if ([[dictCategory objectForKey:@"index"] intValue] == Inspection_Category_Type)
                array = [ScheduleBaseLite queryScheduleByIdCategory:Inspection inStart:startDateStr endDate:endDateStr from:indexSchedule numberPage:NUMBER_ROW_PAGE];
            else
            {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"categoryId",[dictCategory objectForKey:@"index"],@"categoryTypeId", nil];
                array = [ScheduleBaseLite queryScheduleByCategory:dict inStart:startDateStr endDate:endDateStr from:indexSchedule numberPage:NUMBER_ROW_PAGE];
            }
    }
    else{
        
        if ([[dictCategory objectForKey:@"index"] intValue] == 0)
            array = [ScheduleBaseLite queryScheduleByContractor:[userDefaults objectForKey:ACCOUNT_ID] inStart:startDateStr endDate:endDateStr from:indexSchedule numberPage:NUMBER_ROW_PAGE];
        else
            if ([[dictCategory objectForKey:@"index"] intValue] == Inspection_Category_Type)
                array = [ScheduleBaseLite queryScheduleByIdCategory:Inspection byContractor:[userDefaults objectForKey:ACCOUNT_ID] inStart:startDateStr endDate:endDateStr from:indexSchedule numberPage:NUMBER_ROW_PAGE];
            else
            {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:Maintenance],@"categoryId",[dictCategory objectForKey:@"index"],@"categoryTypeId", nil];
                array = [ScheduleBaseLite queryScheduleByCategory:dict byContractor:[userDefaults objectForKey:ACCOUNT_ID] inStart:startDateStr endDate:endDateStr from:indexSchedule numberPage:NUMBER_ROW_PAGE];
            }
    }
    indexSchedule += [array count];

    [arraySchedule addObjectsFromArray:array];
    [self.tbSchedule reloadData];
    
    if ([array count] == NUMBER_ROW_PAGE) {
        isLoadMore = YES;
    }
    if (isLoadMore) {
        [self.tbSchedule showLoadingMore];
    }
    else
        [self.tbSchedule hideLoadingMore];
    [self.tbSchedule hideActivity];
    
    [self performSelector:@selector(hiddenLoading) withObject:nil afterDelay:0.2];
    
    [btnCurtain removeFromSuperview];
}
- (void)updateScheduleInfo:(NSMutableDictionary*)dict isEdit:(BOOL)isEdit{
    if (isEdit)
    {
        int row = [[dict objectForKey:@"indexRow"] intValue];
        [arraySchedule replaceObjectAtIndex:row withObject:dict];
        [self.tbSchedule reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }
    else{
        [arraySchedule addObject:dict];
        [self.tbSchedule insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[arraySchedule count] - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
    }
}
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.translucent = NO;
    [super viewWillAppear:animated];
}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    

    arraySchedule = [[NSMutableArray alloc] init];
    
    //list all schedule
    [self showHiddenActivityProgess:YES];
    
    //create a view to prevent touch when init data
    btnCurtain = [UIButton buttonWithType:UIButtonTypeCustom];
    btnCurtain.frame = CGRectMake(0, 0, 1024, 768);
    [btnCurtain setBackgroundColor:[UIColor whiteColor]];
    btnCurtain.alpha = 0.5;
    [btnCurtain addTarget:self action:@selector(doNothing) forControlEvents:UIControlEventTouchUpInside];
    [ApplicationDelegate.tabBarController.view addSubview:btnCurtain];
    
    [self performSelector:@selector(listScheduleByType) withObject:self afterDelay:0.5];
}

- (void) doNothing {
    //do nothing
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark FilterViewDelegate delegate

- (void)didSelectFilter:(NSMutableDictionary *)filterDict{
    [self didmissPopoverController];
    
    [btnCategory setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
    dictCategory = filterDict;
    [self showHiddenActivityProgess:YES];
    [arraySchedule removeAllObjects];
    indexSchedule = 0;
    [self.tbSchedule reloadData];
    
    [self performSelector:@selector(listScheduleByType) withObject:self afterDelay:0.5];
}

#pragma mark action methods

- (IBAction)btnSwitchCalendarClick:(id)sender {
    
    CalendarScheduleViewController *controller = [[CalendarScheduleViewController alloc] initWithNibName:@"CalendarScheduleViewController" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:controller animated:YES];
}


- (IBAction)selectFromDate:(id)sender {
    UIButton *btnSender = (UIButton *)sender;
    indexSelectDate = StartDateIndex;
    [self didmissPopoverController];
    DatePickerViewController *controller = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:[NSBundle mainBundle] dateSelect:[NSDate date]];
    controller.delegate = self;
    
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:btnSender.frame inView:btnSender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    controller.lblTitleView.text = [dictLanguage objectForKey:@"schedule.title-from-date"];
}

- (IBAction)selectToDate:(id)sender {
    UIButton *btnSender = (UIButton *)sender;
    indexSelectDate = EndDateIndex;
    
    [self didmissPopoverController];
    DatePickerViewController *controller = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:[NSBundle mainBundle] dateSelect:[NSDate date]];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:btnSender.frame inView:btnSender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    controller.lblTitleView.text = [dictLanguage objectForKey:@"schedule.title-to-date"];
}

- (IBAction)selectMaintenanceType:(id)sender {
    
    UIButton *btnSender = (UIButton *)sender;
    
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_scheduleCategory];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:btnSender.frame inView:btnSender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

#pragma mark - DatePickerView Delegate
- (BOOL)validFromDate:(NSString *)fromDate toDate:(NSString *)toDate{
    if (fromDate == nil || toDate == nil)
        return YES;
    NSDate *date1 = [NSDate dateFormatDateDisplayFromString:fromDate];
    NSDate *date2 = [NSDate dateFormatDateDisplayFromString:toDate];
    
    NSString *messageError = nil;
    if (date1 == nil) {
        messageError = [dictLanguage objectForKey:@"schedule.maintenance-schedule-invalid-select-start-date"];
    }
    else if (date2 == nil)
        messageError = [dictLanguage objectForKey:@"schedule.maintenance-schedule-invalid-select-end-date"];
    if ([date1 compare:date2] == NSOrderedDescending) {
        if (indexSelectDate == StartDateIndex) {
            messageError = [dictLanguage objectForKey:@"schedule.maintenance-schedule-invalid-select-start-date"];
        }
        else
            messageError = [dictLanguage objectForKey:@"schedule.maintenance-schedule-invalid-select-end-date"];
    }
    if (messageError == nil)
        return YES;
    else{
        [self showErrorMessage:messageError];
        return NO;
    }
}
- (void)didSelectDatePicker:(NSDate *)date{
    [self didmissPopoverController];
    if (indexSelectDate == StartDateIndex) {
        if (![self validFromDate:[NSDate stringFormatDateDisplayFromDate:date] toDate:endDateStr])
            return;
        
        startDateStr = [NSDate stringFormatDateDisplayFromDate:date];
        [btnStartDate setTitle:startDateStr forState:UIControlStateNormal];
    }
    else{
        if (![self validFromDate:startDateStr toDate:[NSDate stringFormatDateDisplayFromDate:date]])
            return;
        
        endDateStr = [NSDate stringFormatDateDisplayFromDate:date];
        [btnEndDate setTitle:endDateStr forState:UIControlStateNormal];
    }
    [self showHiddenActivityProgess:YES];
    [arraySchedule removeAllObjects];
    indexSchedule = 0;
    [self listScheduleByType];
}
- (void)didCancelSectDatePicker{
    [self didmissPopoverController];
}
#pragma mark - NavViewDelegate

- (void)didClickedLeftButton {
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

- (void)didClickedRightButton
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *permissionDict = [userDefaults objectForKey:SCHEDULE_PERMISSION];
    BOOL isAdd = [[permissionDict objectForKey:@"add"] boolValue];
    if (!isAdd) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
    
    BuildingMgmtViewController *controller = [[BuildingMgmtViewController alloc] initWithNibName:@"BuildingMgmtViewController" bundle:[NSBundle mainBundle] itemType:Building_Type];
    controller.parent = self;
    [self.navigationController pushViewController:controller animated:YES];
//    ScheduleFilterViewController *controller = [[ScheduleFilterViewController alloc] initWithNibName:@"ScheduleFilterViewController" bundle:[NSBundle mainBundle]];
//    [self.navigationController pushViewController:controller animated:YES];
    
}
#pragma mark ScheduleCell delegate


#pragma mark tableview datasource

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [arraySchedule count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellSchedule = @"ScheduleCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellSchedule];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellSchedule];
        
        UILabel *lblCategory = [[UILabel alloc] initWithFrame:CGRectMake(20, 22, WIDTH_COLUMN_ONE, 22)];
        lblCategory.tag = Category_Program_Schedule_Tag;
        lblCategory.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
        lblCategory.textColor = FMS_COLOR_DEFAUL;
        [cell.contentView addSubview:lblCategory];
        
        UILabel *lblMaintenanceType = [[UILabel alloc] initWithFrame:CGRectMake(230, 22, WIDTH_COLUMN_TWO, 22)];
        lblMaintenanceType.tag = Maintenance_Type_Schedule_Tag;
        lblMaintenanceType.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
        lblMaintenanceType.textColor = FMS_COLOR_DEFAUL;
        [cell.contentView addSubview:lblMaintenanceType];
        
        
        UILabel *lblItemType = [[UILabel alloc] initWithFrame:CGRectMake(560, 22, WIDTH_COLUMN_THREE, 22)];
        lblItemType.tag = Item_Type_Schedule_Tag;
        lblItemType.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
        lblItemType.textColor = FMS_COLOR_DEFAUL;
        [cell.contentView addSubview:lblItemType];
        
        UILabel *lblNextDone = [[UILabel alloc] initWithFrame:CGRectMake(750, 22, WIDTH_COLUMN_FOUR, 22)];
        lblNextDone.tag = NextDone_Schedule_Tag;
        lblNextDone.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
        lblNextDone.textColor = FMS_COLOR_DEFAUL;
        [cell.contentView addSubview:lblNextDone];
        
    }

    UILabel *lblCategory = (UILabel *)[cell.contentView viewWithTag:Category_Program_Schedule_Tag];
    UILabel *lblMaintenanceType = (UILabel *)[cell.contentView viewWithTag:Maintenance_Type_Schedule_Tag];
    
    UILabel *lblItemType = (UILabel *)[cell.contentView viewWithTag:Item_Type_Schedule_Tag];
    UILabel *lblNextDone = (UILabel *)[cell.contentView viewWithTag:NextDone_Schedule_Tag];
    
    NSMutableDictionary *scheduleDict = [arraySchedule objectAtIndex:indexPath.row];
    lblCategory.text = [scheduleDict objectForKey:@"scheduleCategory"];
    if ([[scheduleDict objectForKey:@"categoryId"] intValue] == Maintenance){
        lblMaintenanceType.text = [ApplicationDelegate getMaintenanceTypeName:[[scheduleDict objectForKey:@"maintenanceTypeId"] intValue]];
    }
    else
        lblMaintenanceType.text = @"";
    
    if ([[scheduleDict objectForKey:@"itemType"] intValue] == Building_Type) {
        lblItemType.text = [dictLanguage objectForKey:@"schedule.title-building"];
    }
    else
        lblItemType.text = [dictLanguage objectForKey:@"schedule.title-facility"];
    
    lblNextDone.text = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[scheduleDict objectForKey:@"startDate"]]];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    
    NSMutableDictionary *dictSchedule = [arraySchedule objectAtIndex:indexPath.row];
    
    [dictSchedule setObject:[NSNumber numberWithInteger:indexPath.row] forKey:@"indexRow"];
    
    ScheduleInspectionViewController *controller = [[ScheduleInspectionViewController alloc] initWithNibName:@"ScheduleInspectionViewController" bundle:[NSBundle mainBundle] schedule:[dictSchedule mutableCopy]];
    controller.isEditting = YES;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark scrollview load more
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    didReadyLoadMore = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height && !didReadyLoadMore)
    {
        didReadyLoadMore = YES;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (didReadyLoadMore) {
        if(!isLoadMore)
        {
            [self.tbSchedule hideLoadingMore];
            return;
        }
        [self.tbSchedule showActivity];
        [self listScheduleByType];
        
    }
}
@end
